import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import users

from VizSpread.appengine_utilities import sessions

from VizSpread.appengine.contactsparser import ContactsParser
from VizSpread.appengine.contactsloader import ContactsLoader
from VizSpread.appengine import widgets
		
class HomePageView(webapp.RequestHandler):
	def get(self):
		template_values = {}
		template_values['header'] = widgets.LoginWidget().__call__(self.request)
		user = users.get_current_user()	
		session = sessions.Session()
		
		try:
			sets = session['sets']
		except KeyError:
			sets = []
			session['sets'] = sets	
			
		error = self.request.get('error')
		if error:
			if error == "invalid_data":
				errorMessage = "The data format was not recognised. Please check your data and try again."
				template_values['errormessage'] = errorMessage
			if error == "ungeocodeable_data":
				errorMessage = "The data could not be geocoded. Please check your data and try again."
				template_values['errormessage'] = errorMessage
		
		if user == None:		
			datasets = []
			for sessId in sets:
				query = "SELECT * FROM Dataset WHERE sessionId = '%s'" % sessId
				gqlquery = db.GqlQuery(query)
				results = gqlquery.fetch(1)
				if len(results) == 1:
					datasets.append(results[0])
		else:
			query = "SELECT * FROM Dataset WHERE owner = '%s'" % user
			gqlquery = db.GqlQuery(query)
			datasets = gqlquery.fetch(1000)
		
		datasetCount = 0
		for set in datasets:
			datasetCount = datasetCount + 1

		template_values['datasetCount'] = datasetCount
		template_values['datasets'] = datasets

		path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
		self.response.out.write(template.render(path, template_values))

class MapView(webapp.RequestHandler):
	def post(self):
		template_values = {}
		template_values['header'] = widgets.LoginWidget().__call__(self.request)
		session = sessions.Session()
		
		dataSetType = self.request.get('datasettype')
		dataSetName = self.request.get('datasetname')		
		
		if dataSetType == 'new':
			mapCentre = self.request.get('mapcentre')
			dataSetName = self.request.get('datasetname')
			rawData = self.request.get('contactsfile')		

			parser = ContactsParser(dataSetName, mapCentre, rawData)
			
			if not parser.isValidData():
				self.redirect('/?error=invalid_data')
				return
				
			parseSuccess = parser.parseAndStoreGeocodeData()
			if not parseSuccess:
				self.redirect('/?error=ungeocodeable_data')
				return
		
		loader = ContactsLoader(dataSetName)
		loadSuccess = loader.loadDataset()
		
		if not loadSuccess:
			self.redirect('/?error=unloadable_data')
			return

		geodata = loader.getGeodata()
		geodataString = geodata[0]
		geocodeErrors = geodata[1]

		#contactsHtmlTable = loader.getContactsHtmlTable()
		locationsJavascript = """<script type="text/javascript">\n//<![CDATA[\n var geodata = [%s];\n //]]>\n</script>\n""" % geodataString
	
		template_values['mapcentre'] = mapCentre
		#template_values['contacts'] = contactsHtmlTable
		template_values['locations'] = locationsJavascript
		template_values['geocodeerrors'] = geocodeErrors

		path = os.path.join(os.path.dirname(__file__), 'templates/map.html')
		self.response.out.write(template.render(path, template_values))
		
application = webapp.WSGIApplication([('/', HomePageView),
									  ('/map', MapView),], debug=True)
		
def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
	
